package com.hq.ims.data.config.swagger;

import com.hq.web.conf.bean.UserAttribute;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * jiang bai ping
 *
 * @Email 526666031@qq.com
 */
//@Configuration
//@Data
//@EnableWebMvc
//@EnableSwagger2
//@Profile({"dev", "new"})
public class Swagger2Config {

    @Resource
    private UserAttribute userAttribute;

    private String token;

    @Bean
    public Docket systemManagement() {
        return createApi("系统管理", "com.hq.ims.sys.controller");
    }


    /**
     * 创建API
     *
     * @return springfox.documentation.spring.web.plugins.Docket
     * jbp
     */
    public Docket createApi(String groupName, String packageName) {

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()).groupName(groupName)
                .select()
                //这里采用包含注解的方式来确定要显示的接口
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //这里采用包扫描的方式来确定要显示的接口
                .apis(RequestHandlerSelectors.basePackage(packageName))
                .paths(PathSelectors.any())
                .build()
                //***把消息头添加
                .globalOperationParameters(getParameter());
    }

    /**
     * 获取每个组的参数设置
     *
     * @return java.util.List<springfox.documentation.service.Parameter>
     * jbp
     */
    public List<Parameter> getParameter() {
        //在配置好的配置类中增加此段代码即可
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        //name表示名称，description表示描述,required表示是否必填，default value表示默认值
        ticketPar.name("token").defaultValue(token == null ? "" : token).description("用户token")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(true).build();
        //添加完此处一定要把下边的带***的也加上否则不生效
        pars.add(ticketPar.build());
        return pars;
    }

    /**
     * APP信息
     *
     * @return springfox.documentation.service.ApiInfo
     * jbp
     */
    ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("经营一体化项目")
                .description("")
                .version(userAttribute.getSystemVersion())
                .build();
    }
}
